<template>
  <div
    v-loading="loading"
    :class="config.windowSize == 0 ? 'card_group min' : config.windowSize == 1 ? 'card_group mid' : 'card_group big'"
  >
    <div class="cardShow">
      <header>
        <el-tooltip :content="config.name" placement="top-start">
          <span>{{config.name}}</span>
        </el-tooltip>
        <span class="tools">
          <!--表格类型，有对比时间-->
          <el-select
            size="mini"
            v-if="tableType === 2 && config.chartType === 2"
            v-model="tableSelectDate"
            @change="handleChangeTableDate"
            class="select-date-content"
          >
            <el-option v-for="item in tableDateItems" :key="item" :value="item" :label="item"></el-option>
          </el-select>
          <!--图表、表格类型-->
          <!-- <el-select
            size="mini"
            v-model="selectType"
            v-if="dateSelectBool && config.windowSize != 0"
            class="select-type-content"
          >
            <el-option
              v-for="item in dateSelectItems"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select> -->

          <!--漏斗-->
          <template v-if="config.chartType == 4">
            <span
              v-for="item in funnelSelectItems"
              :key="item.value"
              style="cursor: pointer; padding: 0 3px;"
              :class="{'link-none': funnelSelectValue == item.value}"
              @click="handleChangeFunnelType(item)"
            >{{item.label}}</span>
          </template>
          <!-- <i @click="dialog_save = true" class="el-icon-setting"></i> -->
          <!-- <el-dropdown @command="command_change" v-if="config.chartType !== 4"> -->
          <el-dropdown @command="command_change">
            <span class="el-dropdown-link">
              <i class="el-icon-arrow-down el-icon-more"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="0" :disabled="config.chartType !== 3"> 小 </el-dropdown-item>
              <el-dropdown-item :command="1" :disabled="config.chartType == 4"> 中 </el-dropdown-item>
              <el-dropdown-item :command="2"> 大 </el-dropdown-item>
              <el-dropdown-item :command="5">删除</el-dropdown-item>
              <el-dropdown-item :command="4" :disabled="config.chartType == 4">设置</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </header>
      <header>
        <span class="time-range">{{startDate + " 至 " + endDate}}</span>

        <!--漏斗分析：对比时间选项-->
        <div
          class="selected-box"
          :class="config.windowSize == 1 ? 'selected-box-small' : ''"
          v-if="funnelSelectValue === 'overview' &&
					contrastFunnel.opts.length > 0"
        >
          <el-select
            size="mini"
            value-key="ind"
            @change="contrastChange"
            v-model="contrastFunnel.selecteds[0]"
          >
            <el-option
              v-for="item in contrastFunnel.opts"
              :key="item.ind"
              :value="item"
              :label="item.name"
              :title="item.name"
            ></el-option>
          </el-select>

          <span class="vs">VS</span>

          <el-select
            size="mini"
            value-key="ind"
            @change="contrastChange"
            v-model="contrastFunnel.selecteds[1]"
          >
            <el-option
              v-for="item in contrastFunnel.opts"
              :key="item.ind"
              :value="item"
              :label="item.name"
              :title="item.name"
            ></el-option>
          </el-select>
        </div>
      </header>
      <section class="card-sec">
        <template v-if="info.visible">
          <div class="dashboard-number-container">
            <div class="dq_time">{{info.date}}</div>
            <div class="main-number-content">
              <div class="cont">
                <span>{{info.count}}</span>
                次
              </div>
              <!-- 环比、同比-->
              <!--<div class="compare-number-content">
                <div>
                  环比
                  <span :class="config.hb>0?'status_green':'status_red'">
                    <i :class="config.hb>0?'el-icon-caret-top':'el-icon-caret-bottom'"></i>
                    {{config.hb}}%
                  </span>
                </div>
                <div>
                  同比
                  <span :class="config.tb>0?'status_green':'status_red'">
                  <i :class="config.tb>0?'el-icon-caret-top':'el-icon-caret-bottom'"></i>
                  {{config.tb}}%
                  </span>
                </div>
              </div>-->
            </div>
          </div>
        </template>

        <template v-if="config.chartType != 3">
          <!--					<div class="chart-content">-->
          <!-- 2-表格 -->
          <div
            v-show="config.chartType == 2"
            class="table-content"
            :style="{height: info.visible ? '3.9rem' : '5rem'}"
          >
            <el-table
              size="mini"
              border
              :header-cell-style="{background:'#f2f8ff'}"
              :data="tableData"
              height="100%"
              style="width: 100%;"
            >
              <el-table-column
                v-for="item in tableColumn"
                :show-overflow-tooltip="true"
                :sortable="item.sortable"
                :min-width="item.width"
                :key="item.prop"
                :prop="item.prop"
                :label="item.label"
              >
                <template slot-scope="scope">{{scope.row[item.prop] || "--"}}</template>
              </el-table-column>
            </el-table>
          </div>

          <!--4-漏斗-->
          <div
            class="funnel-content"
            v-show="config.chartType == 4"
            v-loading="funnelLoading"
            :style="{height: info.visible ? '3.9rem' : '5rem'}"
          >
            <!-- 趋势 视图 start -->
            <el-row
              :gutter="40"
              v-if="funnelSelectValue === 'trends' && funnelReportResData.funnelDetail"
            >
              <template v-if="config.windowSize == 2">
                <el-col :span="12">
                  <ViewFunnel
                    :funnelReportResData="funnelReportResData"
                    :windowSize="config.windowSize"
                  ></ViewFunnel>
                </el-col>
                <el-col :span="12">
                  <div :id="'chart_funnel' + config.id" class="chart"></div>
                </el-col>
              </template>
              <template v-if="config.windowSize == 1">
                <el-col :span="24">
                  <div :id="'chart_funnel' + config.id" class="chart"></div>
                </el-col>
              </template>
            </el-row>
            <!-- 趋势 视图 end -->

            <!-- 对比|漏斗 视图 start -->
            <el-row
              :gutter="40"
              v-if="funnelSelectValue === 'overview' && funnelReportResData.funnelDetail"
            >
              <!-- 对比-左 -->
              <el-col :span="12">
                <ViewFunnel
                  :windowSize="config.windowSize"
                  :funnelReportResData="funnelReportResData"
                  :byValues="contrastFunnel.selecteds[0]"
                ></ViewFunnel>
              </el-col>

              <!-- 对比-右 -->
              <el-col :span="12">
                <ViewFunnel
                  :windowSize="config.windowSize"
                  :funnelReportResData="funnelReportResData"
                  :byValues="contrastFunnel.selecteds[1]"
                ></ViewFunnel>
              </el-col>
            </el-row>
            <!-- 对比 视图 end -->
          </div>

          <!-- 0、1-图形 -->
          <div
            :id="'chart_event' + config.id"
            class="chart-content"
            v-show="config.chartType == 0 || config.chartType == 1"
          ></div>
          <!--					</div>-->
        </template>
      </section>

      <!-- 编辑弹框 -->
      <el-dialog
        top="12vh"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        class="diglog_setting"
        title="设置"
        :visible.sync="dialog_save"
        width="40%"
      >
        <div class="save_config dialog">
          <div class="line">
            <div class="left">图表类型</div>
            <div class="right">
              <template v-for="item in chartList">
                <span
                  :key="item.value"
                  @click="handleChangeChart(item)"
                  :class="{'type_ech': true, 'type_ech_size': true, 'active': dialog_form.chartType === item.value}"
                >{{item.label}}</span>
              </template>
            </div>
          </div>
          <!--<div class="line">
            <div class="left">同时显示</div>
            <div class="right">
              <el-checkbox-group v-model="show_now" :size="size">
                <el-checkbox label="均值"></el-checkbox>
                <el-checkbox label="合计"></el-checkbox>
                <el-checkbox label="同环比"></el-checkbox>
              </el-checkbox-group>
            </div>
          </div>-->
          <div class="line">
            <div class="left">窗口尺寸</div>
            <div class="right">
              <template v-for="item in sizeList">
                <span
                  :key="item.value"
                  :class="{'type_ech': true, 'type_ech_size': true, 'active': dialog_form.windowSize == item.value}"
                  @click="handleChangeSize(item)"
                >{{item.label}}</span>
              </template>
            </div>
          </div>
          <div class="line">
            <div class="left">显示条数</div>
            <div class="right">
              <el-select size="mini" v-model="dialog_form.limit" clearable>
                <el-option
                  v-for="item in limitList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="line">
            <div class="left">备注</div>
            <div class="right big">
              <el-input v-model="config.bz" type="textarea" :rows="3" :size="size"></el-input>
            </div>
          </div>
        </div>
        <span slot="footer" class="diglog_foot">
          <el-button :size="size" @click="dialog_save = false">取 消</el-button>
          <el-button
            :size="size"
            type="primary"
            :disabled="confirmBtnDisabled"
            @click="handleConfirmConfig"
          >确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { lineData, tableInitData, tableCompareData } from "./mock";
import ElementResize from "@/utils/ElementResize.js";
import ViewFunnel from "../funnelAnalysis/viewFunnel";
import { funnelReportRes } from "../funnelAnalysis/api.config.js";

export default {
  name: "cardShow",
  props: {
    configInit: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  watch: {
    configInit: {
      handler(val) {
        this.handleConfigInit(val);
      },
      deep: true
    }
  },
  created() {
    this.lineData = lineData;
    this.tableInitData = tableInitData;
    this.tableCompareData = tableCompareData;
    this.handleConfigInit(this.configInit);
  },
  mounted() {},
  computed: {
    confirmBtnDisabled() {
      return !(
        this.dialog_form.chartType !== null &&
        this.dialog_form.windowSize !== null
      );
    }
  },
  components: {
    ViewFunnel
  },
  data() {
    return {
      loading: false,
      config: null,
      myChart: null,
      show_now: [],
      size: "small",
      option: null,
      tableColumn: [],
      tableData: [{ id: 1, time: 100, sdkType: "ios" }],
      dialog_save: false, // 窗口开关
      dialog_form: {
        windowSize: null,
        chartType: null,
        limit: null
      },
      initData: [], // 图表数据
      chartList: [
        {
          value: 0,
          label: "线图"
        },
        {
          value: 1,
          label: "柱图"
        },
        {
          value: 2,
          label: "表格"
        },
        {
          value: 3,
          label: "数值"
        },
        // {
        //   value: 4,
        //   label: "环形图"
        // }
      ], // 图表类型list
      sizeList: [
        {
          value: 0,
          label: "小"
        },
        {
          value: 1,
          label: "中"
        },
        {
          value: 2,
          label: "大"
        }
      ], // 窗口大小list
      limitList: [
        {
          label: "前10项",
          value: 10
        },
        {
          label: "前20项",
          value: 20
        },
        {
          label: "前30项",
          value: 30
        },
        {
          label: "前40项",
          value: 40
        },
        {
          label: "前60项",
          value: 60
        },
        {
          label: "前100项",
          value: 100
        }
      ], // 显示项list
      save_config_type: "1",
      // 基础数据
      startDate: "",
      endDate: "",
      info: {
        date: "",
        count: 0,
        visible: false
      }, // 基本信息
      //  表格处理
      dateSelectItems: [
        {
          label: "按月",
          value: "month"
        },
        {
          label: "按周",
          value: "week"
        },
         {
          label: "按天",
          value: "day"
        },
        {
          label: "按时",
          value: "hour"
        },
         {
          label: "按分",
          value: "minute"
        }
      ], // 天/时类型数组
      dateSelectBool: false, // 非漏斗类型：date类型选择框显示
      funnelSelectBool: false, // 漏斗类型选择框显示
      funnelSelectValue: "overview", // 漏斗类型默认值
      funnelSelectItems: [
        {
          label: "漏斗",
          value: "overview"
        },
        {
          label: "趋势",
          value: "trends"
        }
      ],
      /* 对比漏斗 */
      contrastFunnel: {
        opts: [], // 可选对比项
        selecteds: [
          { ind: 0, name: "总体" },
          { ind: 0, name: "总体" }
        ] // 已选
      },
      // funnelData,
      // funnelReportResData: funnelData.funnelReportResData,
      // byValues: funnelData.funnelReportResData.byValues,
      // dateList: funnelData.funnelReportResData.dateList,
      funnelReportResData: {},
      funnelLoading: false,
      /* 趋势图表 */
      chartView: {},
      tableDateItems: [], // 表格日期数组
      selectType: "day", // 天/时类型切换
      tableSelectDate: null, // 表格日期切换
      tableType: 1, // 表格类型
      dateObj: {}, // 表格切换日期：数据处理
      legendList: [], // 图表图例数据
      // 测试数据
      queryJson: {},
      lineData: [],
      tableInitData: [],
      tableCompareData: [],
      seriesArr: [], // 图表渲染数据,
      /* 按xx查看漏斗 & 设置筛选条件 */
      viewFunnelTypes: {
        commonOpts: [],

        arr_check: [], // 按xx查看
        arr_setting: [] // 设置筛选条件
      }
    };
  },
  methods: {
    // 处理configInit
    handleConfigInit(val) {
      this.dateSelectBool = false;
      this.funnelSelectBool = false;
      if (val.chartType == 0 || val.chartType == 1 || val.chartType == 2) {
        this.dateSelectBool = true;
      }
      if (val.chartType == 4) {
        this.funnelSelectBool = true;
        val.windowSize = 2; // 漏斗默认为大
      }

      this.config = Object.assign({}, val);

      let { queryJson } = this.config;

      if (queryJson) {
        queryJson = JSON.parse(queryJson);
        this.queryJson = queryJson;
      }

      // 非漏斗类型
      if (val.chartType != 4) {
        this.data_init();
      } else {
        this.loading = true;
        this.funnelLoading = true;
        this.searchFunnel();
      }
    },
    // 图表、数值初始化
    async data_init() {
      this.loading = true;
      try {
        this.chart_style(this.config.chartType);
        this.myChart.clear();
        this.myChart = null;
      } catch (err) {
        // console.log(err);
      }
      let { queryJson } = this.config;

      if (queryJson) {
        queryJson = JSON.parse(queryJson);
        this.queryJson = queryJson;
      }
      let result = null,
        res;
      // this.loading = false;
      try {
        result = await this.$analysisApi.eventAnalysis.computeEventReport(
          queryJson
        );
        res = result.value;
        this.initData = res;
        this.loading = false;
        this.total_init(queryJson, res);
      } catch (e) {
        this.loading = false;
      }
    },
    // 图形处理
    async total_init(queryJson, res) {
      this.loading = true;
      // 测试数据：无对比时间
      // res = this.lineData;
      // 测试数据：有对比时间
      // res = this.tableCompareData;
      if (this.myChart) {
        this.myChart.clear();
        this.myChart = null;
      }
      // 数值
      if (this.config.chartType === 3) {
        // 测试数据
        // res = this.tableInitData;
        this.num_init(queryJson, res);
        this.info.visible = true;
        this.loading = false;
        return;
      }
      // 表格
      if (this.config.chartType === 2) {
        this.table_init(queryJson, res);
        this.loading = false;
        return;
      }
      if (this.config.chartType != 2 && this.config.chartType != 3) {
        this.$nextTick(() => {
          setTimeout(() => {
            this.myChart = this.$echarts.init(
              document.getElementById("chart_event" + this.config.id),
              "light"
            );

            let { limit } = this.dialog_form;
            // 线图
            if (this.config.chartType === 0) {
              this.chart_init(queryJson, res, "line", limit);
            }
            // 柱图
            if (this.config.chartType === 1) {
              this.chart_init(queryJson, res, "bar", limit);
            }
            // 饼图：不支持无分组
            if (this.config.chartType === 4) {
              this.pie_init(queryJson, res, limit);
            }
            this.loading = false;
            ElementResize.on(
              document.getElementById("chart_event" + this.config.id),
              () => {
                this.myChart.resize();
              }
            );
          }, 200);
        });
      }
    },
    // 基本信息处理
    num_init(queryJson, res) {
      let { series: xAxisArr, rows } = res[0].detailResult;
      let { messures, byFields, searchTime } = queryJson;
      if (xAxisArr.length > 0) {
        this.startDate = searchTime.startDate.slice(0, 10);
        this.endDate = searchTime.endDate.slice(0, 10);

        // info信息：是否显示
        this.info.date = this.endDate;
        if (messures.length <= 1 && byFields.length === 0) {
          this.info.visible = true;
          if (
            rows.length > 0 &&
            rows[rows.length - 1].values &&
            rows[rows.length - 1].values.length > 0
          ) {
            let values = rows[rows.length - 1].values;
            this.info.count = values[values.length - 1][0];
          }
        }
      }
    },
    // table类型处理
    table_init(queryJson, res) {
      let { byFields } = queryJson;
      if (byFields.length === 0) {
        // 测试数据
        // res = this.tableInitData[0];
        this.num_init(queryJson, res);

        let { series: xAxisArr, rows } = res[0].detailResult;
        xAxisArr = this.handle_xAxisArr(xAxisArr);
        this.table_init_one(queryJson, xAxisArr, rows);
      } else {
        // 测试数据
        // res = this.lineData[0];
        this.num_init(queryJson, res);
        let { series: xAxisArr, rows } = res[0].detailResult;
        xAxisArr = this.handle_xAxisArr(xAxisArr);
        this.table_init_two(queryJson, xAxisArr, rows);
      }
    },
    // 处理x轴格式
    handle_xAxisArr(xAxisArr) {
      let dateObj = {};
      // x轴
      if (this.selectType === "day") {
        xAxisArr = xAxisArr.map(item => {
          item = this.$moment(item).format("M-D");
          if (!dateObj[item]) {
            dateObj[item] = [];
          }
          return item;
        });
      } else {
        xAxisArr = xAxisArr.map(item => {
          item = this.$moment(item).format("M-D");
          if (!dateObj[item]) {
            dateObj[item] = [];
          }
          return item;
        });
      }
      this.dateObj = dateObj;
      this.tableDateItems = xAxisArr;
      this.tableSelectDate = xAxisArr[xAxisArr.length - 1];
      return xAxisArr;
    },
    // 没有分组
    table_init_one(queryJson, xAxisArr, rows) {
      let { messures } = queryJson;
      this.tableColumn = [];
      this.tableData = [];
      let columns = [],
        tableData = [];
      columns = [
        {
          prop: "id",
          label: "序号"
        },
        {
          prop: "date",
          label: "日期"
        }
      ];
      messures.map((item, i) => {
        let prop = "measure_" + i;
        let obj = {};
        obj.label = item.name;
        obj.prop = prop;
        columns.push(obj);
      });
      if (rows.length > 0) {
        let values = rows[0].values;
        values.map((value, i) => {
          let obj = {
            id: i + 1
          };
          obj.date = xAxisArr[i];
          value.map((num, j) => {
            let prop = "measure_" + j;
            obj[prop] = num;
          });
          tableData.push(obj);
        });
      }
      this.tableColumn = columns;
      this.tableData = tableData;
    },
    // 有分组情况
    table_init_two(queryJson, xAxisArr, rows) {
      this.tableType = 2;
      let { messures, byFields } = queryJson;
      let columns = [],
        tableData = [];
      // columns处理
      byFields.map(item => {
        let column = {
          prop: item.propertyId,
          label: item.propertyName
        };
        columns.push(column);
      });
      messures.map((item, i) => {
        let column = {
          prop: "measure_" + i,
          label: item.name
        };
        columns.push(column);
      });

      rows.map(row => {
        let { byValues, values } = row;
        values.map((value, j) => {
          let obj = {
            byValues,
            data: value
          };
          this.dateObj[xAxisArr[j]].push(obj);
        });
      });
      tableData = this.handleTableData(queryJson);
      this.tableColumn = columns;
      this.tableData = tableData;
    },
    // 处理表格数据
    handleTableData(queryJson) {
      let { byFields } = queryJson;
      let list = this.dateObj[this.tableSelectDate];
      let tableData = [];
      list.map(item => {
        let obj = {};
        let { byValues, data } = item;
        byValues.map((by_value, i) => {
          obj[byFields[i].propertyId] = by_value;
        });
        data.map((_data, i) => {
          let prop = "measure_" + i;
          obj[prop] = _data;
        });
        tableData.push(obj);
      });
      return tableData;
    },
    // 图表数据生成
    handleLineData(messures, rows, series, type, index = 0) {
      let measureObj = {};

      for (let i = 0; i < rows.length; i++) {
        let obj = {},
          data = [];
        let { byValues, values } = rows[i];
        let name = byValues.join(" ");

        if (messures && messures.length > 0) {
          messures.map((measure, j) => {
            let event_name = "measure_" + j;
            if (!measureObj[event_name]) {
              measureObj[event_name] = {};
            }

            obj = {
              type,
              stack: `measure_${j}_${index}`,
              name: `measure_${j} ` + name
            };
            if (type === "bar") {
              obj.emphasis = {
                focus: "series",
                blurScope: "coordinateSystem"
              };
            }
            this.legendList.push({
              name: `measure_${j} ` + name
            });
            if (!measureObj[event_name][name]) {
              measureObj[event_name][name] = [];
            }
            data = [];
            values.map((value, k) => {
              data.push({
                value: value[j],
                name: series[k]
              });
              measureObj[event_name][name].push(value[j]);
            });
            obj.data = data;
            this.seriesArr.push(obj);
          });
        }
      }
      return measureObj;
    },
    // 折线图、柱状图
    chart_init(queryJson, res, type, limit) {
      let { contrastStartDate } = queryJson.searchTime;
      if (contrastStartDate) {
        this.chart_compare_line(queryJson, res, type, limit);
      } else {
        this.chart_one_line(queryJson, res, type, limit);
      }
    },
    // 无对比时间
    chart_one_line(queryJson, res, type, limit) {
      // 测试数据
      // res = this.lineData;

      let { messures } = queryJson;
      let { series: xAxisArr, rows } = res[0].detailResult;

      // 前n项
      if (limit && limit < rows.length) {
        rows = rows.slice(0, limit);
      }

      this.num_init(queryJson, res);
      // x轴
      xAxisArr = xAxisArr.map(item => {
        return this.$moment(item).format("M-D");
      });
      this.seriesArr = [];
      let currentSeriesIndex;
      this.handleLineData(messures, rows, xAxisArr, type);
      this.myChart.on("mouseover", param => {
        currentSeriesIndex = param.seriesIndex;
      });
      this.option = {
        backgroundColor: "#fff",
        title: {
          text: "",
          textStyle: {
            fontSize: 12,
            fontWeight: 400
          },
          left: "center",
          top: "5%"
        },
        legend: {
          data: this.legendList,
          bottom: 10,
          show: true,
          type: "scroll",
          formatter: params => {
            let nameArr = params.split(" ");
            let _index = nameArr[0].charAt(nameArr[0].length - 1);
            let measureIndex = String.fromCharCode(65 + Number(_index));
            return measureIndex + " " + nameArr.slice(1).join(" ");
          }
        },
        tooltip: {
          trigger: "axis",
          backgroundColor: "#001529",
          textStyle: {
            color: "#fff"
          },
          padding: [10, 10],
          extraCssText: "box-shadow: 1px 0 2px 0 rgba(163,163,163,0.5)",
          position: function(pos, params, dom, rect, size) {
            let obj = { top: pos[1] };
            let flag = pos[0] < size.viewSize[0] / 2;
            if (flag) {
              obj["left"] = pos[0];
            } else {
              obj["right"] = size.viewSize[0] - pos[0];
            }
            return obj;
          },
          enterable: true,
          formatter: params => {
            let resHtml = "";
            params.map(param => {
              let { seriesName, data, color, seriesIndex } = param;
              let nameArr = seriesName ? seriesName.split(" ") : [];
              let _index = nameArr[0].charAt(nameArr[0].length - 1);
              let name =
                messures[_index].name + " " + nameArr.slice(1).join(" ");
              let measureIndex = String.fromCharCode(65 + Number(_index));

              let _html = `<div class="tooltip-content">
                                <div class="name">
                                <span class="name-index" style="background-color: ${color}">${measureIndex}</span>${name}</div>
                                <div class="value">${data.value || "--"}</div>
                             </div>`;
              if (type === "bar") {
                // 柱状图
                if (seriesIndex === currentSeriesIndex) {
                  resHtml += _html;
                }
              } else {
                resHtml += _html;
              }
            });
            let result = `<div class="tooltip-container">${resHtml}</div>`;
            return result;
          }
        },
        grid: {
          left: "10%",
          top: "10%",
          right: "5%"
        },
        xAxis: {
          type: "category",
          boundaryGap: type === "line" ? false : true,
          data: xAxisArr
        },
        yAxis: {
          type: "value"
        },
        series: this.seriesArr
      };
      this.myChart.setOption(this.option, true);
      setTimeout(() => {
        this.myChart.resize();
      }, 100);
    },
    // 有对比时间：对比图
    chart_compare_line(queryJson, res, type, limit) {
      //  测试数据
      // res = this.tableCompareData;

      let xAxisArr = [];
      if (res.length > 1) {
        // x轴
        let res_0 = res[0],
          res_1 = res[1];
        let series_0 = res_0.detailResult.series;
        let series_1 = res_1.detailResult.series;
        series_0 = this.handle_xAxisArr(series_0);
        series_1 = this.handle_xAxisArr(series_1);
        this.num_init(queryJson, res_0);

        let { messures } = queryJson;

        // y轴
        this.seriesArr = [];
        this.legendList = [];
        let measureRes = [];
        res.map((item, index) => {
          let rows = [];
          // 前n项
          if (limit && limit < item.detailResult.rows.length) {
            rows = item.detailResult.rows.slice(0, limit);
          } else {
            rows = item.detailResult.rows;
          }
          let series = this.handle_xAxisArr(item.detailResult.series);
          let measureObj = this.handleLineData(
            messures,
            rows,
            series,
            type,
            index
          );
          measureRes.push(measureObj);
        });

        series_0.map((series, i) => {
          xAxisArr.push(series_0[i] + "/" + series_1[i]);
        });
        let currentSeriesIndex;
        this.myChart.on("mouseover", param => {
          currentSeriesIndex = param.seriesIndex;
        });
        this.option = {
          backgroundColor: "#fff",
          legend: {
            data: this.legendList,
            bottom: 10,
            show: true,
            type: "scroll",
            formatter: params => {
              let nameArr = params.split(" ");
              let _index = nameArr[0].charAt(nameArr[0].length - 1);
              let measureIndex = String.fromCharCode(65 + Number(_index));
              return measureIndex + " " + nameArr.slice(1).join(" ");
            }
          },
          title: {
            text: "",
            textStyle: {
              fontSize: 12,
              fontWeight: 400
            },
            left: "center",
            top: "5%"
          },
          tooltip: {
            trigger: "axis",
            backgroundColor: "#001529",
            textStyle: {
              color: "#fff"
            },
            padding: [10, 10],
            extraCssText: "box-shadow: 1px 0 2px 0 rgba(163,163,163,0.5)",
            position: function(pos, params, dom, rect, size) {
              let obj = { top: pos[1] };
              let flag = pos[0] < size.viewSize[0] / 2;
              if (flag) {
                obj["left"] = pos[0];
              } else {
                obj["right"] = size.viewSize[0] - pos[0];
              }
              return obj;
            },
            enterable: true,
            formatter: params => {
              // console.log(params);
              let obj = {};
              let axisValueArr = params[0].axisValue.split("/");
              let resHtml;
              params.map(param => {
                let { seriesName, data, color, seriesIndex } = param;
                if (!obj[seriesName]) {
                  obj[seriesName] = {
                    seriesIndex: []
                  };
                }
                obj[seriesName].seriesIndex.push(seriesIndex);
                if (data.name === axisValueArr[0]) {
                  obj[seriesName].firstDate = data;
                } else if (data.name === axisValueArr[1]) {
                  obj[seriesName].secondDate = data;
                }
                obj[seriesName].color = color;
              });

              resHtml = `<div class="tooltip-content"><div class="name">指标及分组值</div><div class="value">${axisValueArr[0]}</div><div class="value">${axisValueArr[1]}</div></div>`;
              for (let i in obj) {
                let nameArr = i ? i.split(" ") : [];
                let _index = nameArr[0].charAt(nameArr[0].length - 1);
                let name =
                  messures[_index].name + " " + nameArr.slice(1).join(" ");
                let measureIndex = String.fromCharCode(65 + Number(_index));
                let _html = `<div class="tooltip-content">
                               	 <div class="name">
																	 <span class="name-index" style="background-color: ${
                                     obj[i].color
                                   }">${measureIndex}</span>${name}
                                 </div>
                                 <div class="value">${obj[i].firstDate.value ||
                                   "--"}</div>
                                 <div class="value">${obj[i].secondDate.value ||
                                   "--"}</div>
                               </div>`;
                if (type === "bar") {
                  // 柱状图
                  if (obj[i].seriesIndex.indexOf(currentSeriesIndex) > -1) {
                    resHtml += _html;
                  }
                } else {
                  resHtml += _html;
                }
              }

              let result = `<div class="tooltip-container">${resHtml}</div>`;
              return result;
            }
          },
          grid: {
            left: "10%",
            top: "10%",
            right: "5%"
          },
          xAxis: {
            type: "category",
            boundaryGap: type === "line" ? false : true,
            data: xAxisArr
          },
          yAxis: {
            type: "value"
          },
          series: this.seriesArr
        };
        this.myChart.setOption(this.option, true);
        setTimeout(() => {
          this.myChart.resize();
        }, 100);
      }
    },
    // 饼图数据
    pie_data(queryJson, res, limit) {
      this.legendList = [];
      let { messures } = queryJson;
      let { rows } = res.detailResult;
      // 前n项
      if (limit && limit < rows.length) {
        rows = rows.slice(0, limit);
      }
      messures.map((messure, i) => {
        messure.data = [];
        rows.map(row => {
          let { values, byValues } = row;
          let name = byValues.join(",");
          if (this.legendList.indexOf(name) === -1) {
            this.legendList.push(name);
          }
          let obj = {
            name,
            value: 0
          };
          values.map(value => {
            obj.value += Number(value[i]);
          });
          messure.data.push(obj);
        });
      });
      return messures;
    },
    // 生成饼图
    pie_init(queryJson, res, limit) {
      let data = this.pie_data(queryJson, res[0], limit);
      this.num_init(queryJson, res);
      let {
        startDate,
        endDate,
        contrastStartDate,
        contrastEndDate
      } = queryJson.searchTime;
      let seriesData = [],
        contrastData = [];
      if (contrastStartDate) {
        contrastData = this.pie_data(queryJson, res[1], limit);
      }
      let temp =
        100 / (Math.floor((data.length + contrastData.length - 1) / 2) + 1);
      let titleArr = [];
      for (let i = 0; i < data.length; i++) {
        let item = {};
        item.name = data[i].name;
        item.type = "pie";
        item.radius = [40, 70];
        item.data = data[i].data;
        seriesData.push(item);
        if (contrastStartDate) {
          let obj = JSON.parse(JSON.stringify(item));
          obj.data = contrastData[i].data;
          seriesData.push(obj);
        }
      }
      seriesData.map((item, i) => {
        item.type = "pie";
        let x = i % 2 ? "75%" : "25%";
        let msg;
        let top = temp * Math.floor(i / 2);
        let text_top = top; // text的top值
        let text_h = 4; // text的高度
        let subtext_h = 2; // subtext所占据的高度
        let radius_top = top + (temp - text_h - subtext_h) / 2 - 10; // 饼图中心高度
        let radius_center = (temp - text_top - text_h - subtext_h) / 2; // 饼图半径
        let subtext_top = top + temp - 30;
        item.center = [radius_center - 10 + "%", radius_center + "%"];
        let subtext = item.name;
        let title = {};
        if (contrastStartDate) {
          if (!(i % 2)) {
            title = {
              text: item.name,
              top: text_top + "%",
              left: "center"
            };
            titleArr.push({ ...title });
          }
          subtext =
            i % 2
              ? contrastStartDate + "至" + contrastEndDate
              : startDate + "至" + endDate;
        }
        title = {
          subtext,
          subtextStyle: {
            fontWeight: 500,
            fontSize: 14,
            color: "#2c3e50"
          },
          textAlign: "center",
          left: x
        };
        msg = {
          top: subtext_top + "%",
          subtext
        };
        titleArr.push({ ...title, ...msg });
        item.center = [x, radius_top + "%"];
      });
      let h = Math.ceil((data.length + contrastData.length) / 2) * 115 + "%";
      this.chart_style(this.config.chartType, h);
      this.option = {
        backgroundColor: "#fff",
        title: titleArr,
        legend: {
          data: this.legendList,
          bottom: 10,
          show: true,
          type: "scroll"
        },
        tooltip: {
          trigger: "item",
          backgroundColor: "#001529",
          textStyle: {
            color: "#fff"
          },
          padding: [10, 10],
          enterable: true,
          formatter: params => {
            // console.log(params);
            let { seriesName, data, color, percent } = params;
            let resHtml = `
								<div class="tooltip-content">
									<div class="name">${seriesName}</div>
								</div>
								<div class="tooltip-content">
									<div class="name">
										<span class="name-index"
											style="background-color: ${color}">
										</span>${data.name}
									 </div>
									 <div class="value">${data.value || "--"}</div>
									 <div class="value">${percent + "%" || "--"}</div>
								</div>
              `;
            let result = `<div class="tooltip-container pie-tooltip-container">${resHtml}</div>`;
            return result;
          }
        },
        grid: {
          left: "10%",
          top: "5%",
          bottom: "0",
          right: "5%"
        },
        series: seriesData
      };
      this.myChart.setOption(this.option, true);
      setTimeout(() => {
        this.myChart.resize();
      }, 100);
    },
    // 图形高度
    chart_style(type, h) {
      let pie_chart = document.querySelector("#chart_event" + this.config.id);
      if (type === 4) {
        pie_chart.style.height = h;
      } else {
        pie_chart.style.height = "100%";
      }
    },
    // 改变command
    command_change(key) {
      switch (key) {
        case 0:
        case 1:
        case 2:
          this.config.windowSize = key;
          break;
        case 4:
          if (this.config.chartType != 4) {
            this.dialog_save = true;
            this.dialog_form.windowSize = this.config.windowSize;
            this.dialog_form.chartType = this.config.chartType;
          }
          break;
        case 5: // 删除关键字
          this.$emit("del_card");
          break;
        default:
          break;
      }
    },
    // table: 日期改变
    handleChangeTableDate() {
      this.tableData = this.handleTableData(this.queryJson);
    },
    // 图表类型改变
    handleChangeChart(item) {
      let _change = true;
      if (this.dialog_form.windowSize == 0) {
        this.dialog_form.windowSize = null;
        this.confirmBtnDisabled = true;
      }
      // 环形图
      if (item === 4) {
        let { byFields } = this.queryJson;
        if (!byFields || byFields.length === 0) {
          _change = false;
          this.$message.warning("当前没有分组条件，不支持环形图");
        } else {
          this.dialog_form.windowSize = 2;
        }
      }
      if (_change) {
        this.dialog_form.chartType = item.value;
      }
    },
    // 窗口大小改变
    handleChangeSize(item) {
      let { value } = item;
      if (this.dialog_form.chartType !== 3 && value === 0) {
        this.$message.warning("当前类型不支持小窗口尺寸");
      } else if (this.dialog_form.chartType === 4 && value === 1) {
        this.$message.warning("当前类型不支持中窗口尺寸");
      } else {
        this.dialog_form.windowSize = value;
      }
    },
    handleConfirmConfig() {
      let { windowSize, chartType } = this.dialog_form;
      this.config.windowSize = windowSize;
      this.config.chartType = chartType;
      this.dialog_save = false;
      this.total_init(this.queryJson, this.initData);
    },
    // 切换漏斗类型
    handleChangeFunnelType(item) {
      this.funnelSelectValue = item.value;
      // 趋势图
      if (item.value == "trends") {
        this.$nextTick(() => {
          setTimeout(() => {
            this.viewChart();
          }, 300);
        });
      }
    },
    // 切换对比时间
    contrastChange() {},
    /* 初始化对比选项 */
    initContrastFunnelOpts() {
      let t = this;
      t.contrastFunnel.opts = [];
      t.contrastFunnel.selecteds = [
        { ind: 0, name: "总体" },
        { ind: 0, name: "总体" }
      ];

      // if (t.viewFunnelTypes.arr_check.length <= 0) {
      // 	return;
      // }

      let byValuesList = t.funnelReportResData.byValuesList;
      for (let i = 0; i < byValuesList.length; i++) {
        let arr = byValuesList[i];
        let str = "";

        for (let j = 0; j < arr.length; j++) {
          let val = arr[j];
          str = str + val + (j === arr.length - 1 ? "" : ", ");
        }
        if (i === 0) {
          t.contrastFunnel.opts.push({ ind: 0, name: "总体" });
        } else {
          t.contrastFunnel.opts.push({ ind: i, name: str });
        }
      }
      console.log("t.contrastFunnel", t.contrastFunnel);

      // 默认总体
      t.contrastFunnel.selecteds[0] = t.contrastFunnel.opts[0];
      t.contrastFunnel.selecteds[1] = t.contrastFunnel.opts[1];
    },

    /* 查询漏斗内容 */
    searchFunnel() {
      let t = this;
      this.funnelLoading = true;
      let appid = this.$store.state.global.appItem
        ? this.$store.state.global.appItem.appId
        : null;

      let param = {
        // id: t.analysisOpts.value.id,
        //
        // funnelId: t.analysisOpts.value.id, // 当前已选漏斗 id
        // byFields: t.getByFields(), // 按 xx 查看
        //
        // filter: this.$refs.customScreenRef.getFilterConditions(), // 自定义漏斗筛选
        //
        // fromDate: t.winPeriod[0], // 窗口期 开始时间
        // toDate: t.winPeriod[1], // 窗口期 结束时间
        //
        // sub_task_type: "FUNNEL", // 漏斗模块写死的值
        //
        // // TODO 以下字段前期默认空值
        // byFieldSteps: [],
        // filterFieldSteps: [],
        // bucketParams: {},
        // bookmarkid: ""
      };

      param = JSON.parse(this.config.queryJson);
      console.log(param, "param");
      console.log(appid, "appid");
      try {
        funnelReportRes(param)
          .then(res => {
            console.log("漏斗内容 = ", res.data);

            // TODO 特殊接口，暂不需要弹窗提示
            // if (res.code !== 200) {
            //   t.loading = false;
            //   this.$alert(res.data.msg, '提示', { type: 'warning'});
            //   return;
            // }

            // 接口返回成功后 loading 150 毫秒后消失，因为太快消失的话用户看不见 loading，一闪而过了

            t.funnelReportResData = res.data.value || {};
            t.funnelTimeInit(res.data.value || {});
            t.initContrastFunnelOpts();

            setTimeout(() => {
              t.viewChart();
            });
            setTimeout(() => {
              t.loading = false;
              t.funnelLoading = false;
            }, 150);
          })
          .catch(error => {
            t.funnelLoading = false;
            t.loading = false;
            console.log("error = ", error);
          });
      } catch (e) {
        t.funnelLoading = false;
        t.loading = false;
      }
    },

    /* 渲染图表 */
    viewChart() {
      let t = this;

      // 如果当前是 对比或漏斗 视图，则不需要展示图表
      if (t.funnelSelectValue === "overview") {
        return;
      }

      let dom = document.getElementById("chart_funnel" + this.config.id);
      t.chartView = t.$echarts.init(dom);

      // 图表模板
      let tem = {
        xAxis: {
          type: "category",
          axisLabel: { interval: 0, rotate: -40 },
          data: []
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: []
        },
        yAxis: {
          type: "value",
          axisLabel: {
            formatter: "{value} %"
          }
        },
        series: []
      };

      console.log("funnelReportResData ===> ", funnelReportResData);
      let funnelReportResData = t.funnelReportResData;
      let dateList = funnelReportResData.dateList;
      let funnelDetail = funnelReportResData.funnelDetail;
      let events = funnelReportResData.events;

      // 图表横坐标，因为 dateList 第 0 个是 '$ALL'，所以从第 1 个开始
      for (let i = 1; i < dateList.length; i++) {
        tem.xAxis.data.push(dateList[i]);
      }
      // 步骤
      for (let i = 0; i < events.length; i++) {
        let size = i === 0 ? "总体转化" : "第 " + i + " 步转化";
        tem.legend.data.push(size);
        tem.series.push({
          name: size,
          type: "line",
          data: [],

          // 参考线/辅助线
          markLine: { data: [{ type: "average", name: "平均值" }] }
        });
      }

      // 坐标值
      for (let i = 1; i < dateList.length; i++) {
        let item = funnelDetail[i];

        for (let j = 0; j < item.steps.length; j++) {
          let cItem = item.steps[j];
          if (j === 0) {
            tem.series[j].data.push(item.completionRate);
          } else {
            tem.series[j].data.push(cItem.conversionRate);
          }
        }
      }

      this.$nextTick(() => {
        t.chartView.clear();
        t.chartView.setOption(tem);
        t.autoChart();
      });
    },
    // 时间范围
    funnelTimeInit(res) {
      let { dateList } = res;
      console.log("dateList ====>>", dateList);

      if (dateList.length == 2) {
        this.startDate = dateList[1];
        this.endDate = dateList[1];
      } else if (dateList.length > 2) {
        this.startDate = dateList[1];
        this.endDate = dateList[dateList.length - 1];
      }
    },

    /* 图表大小自适应 */
    autoChart() {
      // 如果当前是 对比 视图，则不需要渲染图表
      // if (this.funnelSelectValue === "overview") {
      // 	return;
      // }
      console.log(this.chartView, "chartView");
      this.chartView && this.chartView.resize();
    }
  }
};
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}

::v-deep .tooltip-container {
  max-height: 60vh;
  overflow: auto;
}

::v-deep .tooltip-content {
  display: flex;

  .name {
    flex-grow: 1;
    margin-right: 10px;

    .name-index {
      margin-right: 5px;
      width: 20px;
      height: 20px;
      display: inline-block;
      line-height: 20px;
      text-align: center;
      -webkit-border-radius: 50%;
      -moz-border-radius: 50%;
      border-radius: 50%;
    }
  }

  .value {
    width: 80px;
  }
}

::v-deep .pie-tooltip-container {
  .name {
    .name-index {
      width: 10px;
      height: 10px;
      line-height: 10px;
    }
  }
}

::v-deep .cardShow {
  width: 100%;
  margin: 0 auto;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;

  header {
    width: 98%;
    margin: 0 auto;
    position: relative;

    .select-date-content {
      width: 120px;
      margin-right: 5px;
    }

    .select-type-content {
      input.el-input__inner {
        width: 60px;
        padding: 0 0 0 10px;
        margin-right: 5px;
      }
    }

    .tools {
      margin-top: 5px;
      position: absolute;
      right: 0;
      top: 0;
      height: 100%;
      padding: 0 0.1rem 0 0;

      .el-icon-more {
        cursor: pointer;
        font-size: 0.26rem;
      }

      .el-icon-more:hover {
        font-weight: 800;
        color: rgba($color: #01b27a, $alpha: 0.8);
      }
    }
  }

  header:nth-child(1) {
    height: 0.5rem;
    text-indent: 0.1rem;
    font-weight: 500;
    line-height: 0.5rem;
  }

  header:nth-child(2) {
    height: 0.5rem;
    line-height: 0.5rem;
    .time-range {
      text-indent: 0.1rem;
      font-size: 10px;
    }
    .selected-box {
      transform: scale(0.95);
      position: absolute;
      right: 0rem;
      top: 0.1em;
      margin-bottom: 0.1rem;
      .vs {
        margin: 0 5px;
        font-size: 12px;
      }

      &.selected-box-small {
        .el-select {
          width: 120px;
        }
      }
    }
  }

  footer {
    width: 98%;
    margin: 0 auto;
    height: 0.5rem;
    font-size: 0.2rem;
    cursor: pointer;
    line-height: 0.5rem;
    padding: 0 0.1rem;

    span {
      margin: 0 0.2rem;
      letter-spacing: 1px;
    }
  }

  .card-sec {
    width: 98%;
    margin: 0 auto;
    /*flex: 1;*/
    flex-grow: 1;
    display: flex;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    flex-direction: column;
    justify-content: center;
    // height: calc(100% - 1.3rem);
    .chart-content {
      flex-grow: 1;
      flex-flow: column;
      /*height: 0;*/
      margin: 0.2rem 0;
      overflow-x: hidden;
      overflow-y: auto;
    }
    .table-content {
      /*flex-grow: 1;*/
      margin: 0.2rem 0;
      overflow-x: hidden;
      overflow-y: hidden;
      /*height: 0;*/
      .el-table {
        margin: 0;
        height: 100%;
      }
    }
    .funnel-content {
      margin: 0.2rem 0;
      overflow-x: hidden;
      overflow-y: auto;
    }

    .dq_time {
      width: 100%;
      height: 0.4rem;
      line-height: 0.4rem;
      font-size: 0.2rem;
      color: rgba($color: #909399, $alpha: 0.6);
      text-indent: 0.1rem;
    }

    .cont {
      font-size: 0.2rem;
      text-indent: 0.2rem;
      height: 0.7rem;
      line-height: 0.7rem;

      span {
        font-size: 0.6rem;
        /*line-height: 1rem;*/
        margin-right: 0.2rem;
      }
    }

    .ech {
      width: 100%;
      height: 100%;
    }
  }
}

::v-deep .card_group {
  .compare-number-content {
    font-size: 0.2rem;
    cursor: pointer;
    /*height: 0.5rem;*/
    /*line-height: 0.5rem;*/
    padding: 0 0.1rem;
  }

  &.min {
    .compare-number-content {
      width: 98%;
      margin: 0 auto;

      & > div {
        float: left;

        span {
          margin: 0 0.2rem;
          letter-spacing: 1px;
        }
      }
    }
  }

  &.mid,
  &.big {
    .main-number-content {
      display: flex;
      align-items: center;
    }
  }
}

// 弹窗
::v-deep .diglog_setting {
  .save_config {
    width: 100%;

    .line {
      width: 99%;
      margin: 0.2rem auto;
      display: flex;
      justify-content: space-between;

      .left {
        width: 20%;
        height: 100%;
        text-indent: 10px;
        height: 0.8rem;
        letter-spacing: 2px;
        font-size: 12px;
        display: flex;
        align-items: center;
      }

      .right {
        height: 100%;
        width: 80%;
        min-height: 0.8rem;
        display: flex;
        align-items: center;

        .type_ech {
          cursor: pointer;
          min-width: 0.6rem;
          height: 0.6rem;
          display: inline-block;
          margin: 0 0.2rem 0 0;
          text-align: center;
          line-height: 0.6rem;
          font-size: 10px;
          border-radius: 4px;
          border: 1px solid rgba($color: #e4e7ed, $alpha: 0.8);
          color: rgba($color: #e4e7ed, $alpha: 1);
        }

        .active {
          border: 1px solid rgba($color: #01b27a, $alpha: 0.6);
          color: rgba($color: #01b27a, $alpha: 0.8);
        }

        .type_ech:hover {
          border: 1px solid rgba($color: #01b27a, $alpha: 0.6);
          color: rgba($color: #01b27a, $alpha: 0.8);
        }

        .type_ech_size {
          min-width: 0.8rem;
          height: 0.8rem;
          line-height: 0.8rem;
          padding: 0 3px;
        }
      }

      .big {
        height: 2rem;
      }
    }
  }
}
</style>

<style scoped lang="scss">
.el-container .el-main {
  text-align: center;
  background-color: transparent;
}

.chart {
  width: 100%;
  height: 5rem;
  position: relative;
}
</style>
